package org.leslie.controller;

import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.leslie.pojo.Result;
import org.leslie.pojo.User;
import org.leslie.service.UserService;
import org.leslie.utils.JwtUtil;
import org.leslie.utils.Md5Util;
import org.leslie.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result<?> register(@Pattern(regexp = "^\\S{5,16}$") String username,
                              @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.findByUserName(username);
        if (user == null) {
            userService.register(username, password);
            return Result.success();
        } else {
            return Result.error("Username has been taken");
        }
    }


    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,
                                @Pattern(regexp = "^\\S{5,16}$") String password) {
        // 查询用户
        User loginUser = userService.findByUserName(username);
        // 用户是否存在
        if (loginUser == null) {
            return Result.error("Username is not exist");
        }

        // password is correct
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);

            // 把 token 存储到 redis中
            ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
            valueOperations.set(token, token, 1, TimeUnit.HOURS);
            return Result.success(token);
        }

        return Result.error("password error");
    }

    @GetMapping("/userinfo")
    public Result<User> userinfo(/*@RequestHeader(name = "Authorization") String token*/) {
        // 根据用户名查询信息: 从线程中获取用户名
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result<?> update(@RequestBody @Validated User user) {
        User targetUser = userService.findByUserId(user.getId());
        if (targetUser != null) {
            userService.update(user);
            return Result.success();
        } else {
            return Result.error("User id is not exist");
        }
    }

    @PatchMapping("/updateAvatar")
    public Result<?> updateAvatar(@RequestParam("avatar") @URL String avatar) {
        userService.updateAvatar(avatar);
        return Result.success();
    }

    @PatchMapping("/updatePassword")
    public Result<?> updatePassword(@RequestBody Map<String, Object> params, @RequestHeader("Authorization") String token) {
        // 1.校验参数
        String oldPassword = (String) params.get("oldPassword");
        String newPassword = (String) params.get("newPassword");
        String confirmPassword = (String) params.get("confirmPassword");

        if (!StringUtils.hasLength(oldPassword) ||
                !StringUtils.hasLength(newPassword) ||
                !StringUtils.hasLength(confirmPassword)) {
            return Result.error("Not enough information");
        }
        // 2. 原密码是否正常
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPassword))) {
            return Result.error("Old password is not correct");
        }
        // 3. 校验 newPassword 和 confirmPassword
        if (!confirmPassword.equals(newPassword)) {
            return Result.error("Password is not matched");
        }
        // 4. 调用 service 完成更新
        userService.updatePassword(newPassword);

        // 删除 redis 中对应的token.
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.getOperations().delete(token);
        return Result.success();
    }
}

